package com.hongx.plugin;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.hongx.plugin.core.common.GetImagePath;
import com.hongx.plugin.core.widget.CustomDialog;
import com.hongx.plugin.utils.LogUtil;
import com.hongx.plugin.utils.UtilAnim;
import com.hongx.plugin.utils.UtilBitmap;
import com.hongx.plugin.utils.UtilScreenCapture;

import java.io.ByteArrayOutputStream;
import java.io.File;


/**
 * Created by Administrator on 2017/2/12 0012.
 */

public class PersonInfoActivity
        extends BaseActivity
        implements View.OnClickListener{

    private TextView title;

    private Uri imageUri;
    private final String IMAGE_FILE_NAME = "picture.jpg";// 照片文件名称
    private String urlpath; // 图片本地路径
    private final int REQUESTCODE_PICK = 0; // 相册选图标记
    private final int REQUESTCODE_TAKE = 1; // 相机拍照标记
    private final int REQUESTCODE_CUTTING = 2; // 图片裁切标记

    private ImageView iv_popup_window_back;
    private RelativeLayout rl_popup_window;

    private Button takePhotoBtn, pickPhotoBtn, cancelBtn;
    private Bitmap upBitmap;

    private LinearLayout ll_back;

//    private ListenerInputView nameEdit;
    private ImageView headerImageView;
    private RelativeLayout rl_header;

    @Override
    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_info);


        initView();
    }

    private void initView(){
//        title = (TextView) findViewById(R.id.mainUI_title_titleText);
//        title.setText("个人信息");

        imageUri = Uri.parse("file:///sdcard/temp.jpg");
        iv_popup_window_back = (ImageView) findViewById(R.id.popupWindow_back);
        rl_popup_window = (RelativeLayout) findViewById(R.id.popupWindow);

        takePhotoBtn = (Button) findViewById(R.id.takePhotoBtn);
        pickPhotoBtn = (Button)findViewById(R.id.pickPhotoBtn);
        cancelBtn = (Button)findViewById(R.id.cancelBtn);

        takePhotoBtn.setOnClickListener(itemsOnClick);
        pickPhotoBtn.setOnClickListener(itemsOnClick);
        cancelBtn.setOnClickListener(itemsOnClick);



//        ll_back = (LinearLayout) findViewById(R.id.ll_backBtn);
        rl_header = (RelativeLayout)findViewById(R.id.rl_header);
        headerImageView = (ImageView)findViewById(R.id.iv_header);
//        nameEdit = (ListenerInputView)findViewById(R.id.settingUI_name);
//
//
//        nameEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
////                nickname = nameEdit.getText().toString();
//                LogUtil.e("onFocusChange===", nameEdit.getText().toString()+"==="+hasFocus);
//
////                if(!hasFocus){
////                    submit_nickname();
////                }
//            }
//        });
//
//        nameEdit.setOnTouchListener(new View.OnTouchListener() {
//            public boolean onTouch(View v, MotionEvent event) {
//                LogUtil.e("onTouch===", nameEdit.getText().toString()+"===");
//
////                if(isFirst){
////                    isFirst = false;
////                    nickname0 = nameEdit.getText().toString();
////                }
//
//
//                nameEdit.setFocusable(true);
//                nameEdit.setFocusableInTouchMode(true);
//                nameEdit.requestFocus();
//                return false;
//            }
//        });
//
////        nameEdit.setShowSoftInputOnFocus(true);
//
//        nameEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//            @Override
//            public void onFocusChange(View v, boolean hasFocus) {
//                LogUtil.e("onFocusChange===", "==="+hasFocus);
//            }
//        });


//        ll_back.setOnClickListener(this);
        rl_header.setOnClickListener(this);


//        initHttp();
//        admission_time();
//        getUpToken();
//        colleges();
    }

    @Override
    public void onClick(View v) {
//        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//        inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
//
//        LogUtil.e("onClick===", v+"===");
//
//        nameEdit.setFocusable(false);

        switch (v.getId()){
//            case R.id.ll_backBtn:
//                that.finish();
//                break;

            case R.id.rl_header:
                clickPopupWindow();
                break;

            case R.id.rl_phoneNum:
//                UIHelper.goToAct(context, ChangePhoneNumActivity.class);
                break;

        }
    }


    public void initHttp() {
        Log.e("pia===initHttp", "===");

    }

    private void clickPopupWindow() {
        // 获取截图的Bitmap
        Bitmap bitmap = UtilScreenCapture.getDrawing(this);

        Log.e("pia===clickPopupWindow", "==="+bitmap);

        if (bitmap != null) {
            // 将截屏Bitma放入ImageView
            iv_popup_window_back.setImageBitmap(bitmap);
            // 将ImageView进行高斯模糊【25是最高模糊等级】【0x77000000是蒙上一层颜色，此参数可不填】
//            UtilBitmap.blurImageView(context, iv_popup_window_back, 25, 0x77000000);
            UtilBitmap.blurImageView(context, iv_popup_window_back, 5, 0xAA000000);
        } else {
            // 获取的Bitmap为null时，用半透明代替
            iv_popup_window_back.setBackgroundColor(0x77000000);
        }

//        Glide.with(this)
//                .load(R.drawable.app_icon)
////                .apply(bitmapTransform(new BlurTransformation(50)))
//                .bitmapTransform(new BlurTransformation(this, 14, 3))
//                .into(iv_popup_window_back);
//
//        iv_popup_window_back.setVisibility(View.VISIBLE);

        // 打开弹窗
        UtilAnim.showToUp(rl_popup_window, iv_popup_window_back);
    }

    private void clickClosePopupWindow() {
        UtilAnim.hideToDown(rl_popup_window, iv_popup_window_back);
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @SuppressLint("NewApi")
        @Override
        public void onClick(View v) {
            clickClosePopupWindow();
            switch (v.getId()) {
                // 拍照
                case R.id.takePhotoBtn:
                    if (Build.VERSION.SDK_INT >= 23) {
                        int checkPermission = that.checkSelfPermission(Manifest.permission.CAMERA);
                        if (checkPermission != PackageManager.PERMISSION_GRANTED) {
                            if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
                                requestPermissions(new String[]{Manifest.permission.CAMERA}, 101);
                            } else {
                                CustomDialog.Builder customBuilder = new CustomDialog.Builder(context);
                                customBuilder.setTitle("温馨提示").setMessage("您需要在设置里打开相机权限！")
                                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.cancel();
                                            }
                                        }).setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                        requestPermissions(new String[]{Manifest.permission.CAMERA},
                                                101);

                                    }
                                });
                                customBuilder.create().show();
                            }
                            return;
                        }
                    }

                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                        Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

//                        File file = new File(Environment.getExternalStorageDirectory()+"/images/", IMAGE_FILE_NAME);
                        File file = new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME);
                        if(!file.getParentFile().exists()){
                            file.getParentFile().mkdirs();
                        }

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(context, that.getPackageName() + ".fileprovider", file));

                        }else {
                            takeIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                        }


                        that.startActivityForResult(takeIntent, REQUESTCODE_TAKE);
                    }else {
                        Toast.makeText(context,"未找到存储卡，无法存储照片！",Toast.LENGTH_SHORT).show();
                    }

                    break;

                // 相册选择图片
                case R.id.pickPhotoBtn:
//                    Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                        Intent intent;
                        if (Build.VERSION.SDK_INT < 19) {
                            intent = new Intent(Intent.ACTION_GET_CONTENT);
                            intent.setType("image/*");
                        } else {
                            intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        }
                        that.startActivityForResult(intent, REQUESTCODE_PICK);
                    } else {
                        Toast.makeText(context, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
                    }

                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        Log.e("pia=onActivityResult", requestCode+"==="+resultCode);

        switch (requestCode) {
            case 10:
                if (resultCode == RESULT_OK) {
//                    codenum = data.getStringExtra("codenum");
//                    m_nowMac = data.getStringExtra("m_nowMac");


                } else {
//                    Toast.makeText(context, "扫描取消啦!", Toast.LENGTH_SHORT).show();
                }
                break;

            case REQUESTCODE_PICK:// 直接从相册获取

                if (resultCode == RESULT_OK) {

                    if (data != null) {
                        try {
                            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                                Log.e("minef=REQUESTCODE_PICK", Build.VERSION.SDK_INT+"==="+data.getData());

                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    File imgUri = new File(GetImagePath.getPath(context, data.getData()));

                                    Log.e("minef=REQUESTCODE_PICK2", imgUri+"==="+ getPackageName());

                                    Uri dataUri = FileProvider.getUriForFile(context, getPackageName() + ".fileprovider", imgUri);

                                    Log.e("minef=REQUESTCODE_PICK3", imgUri+"==="+dataUri);

                                    startPhotoZoom(dataUri);
                                } else {
                                    startPhotoZoom(data.getData());
                                }
                            } else {
                                Toast.makeText(context, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
                            }
                        } catch (NullPointerException e) {
                            e.printStackTrace();// 用户点击取消操作
                        }
                    }


                } else {
//                    Toast.makeText(context, "扫描取消啦!", Toast.LENGTH_SHORT).show();
                }



                break;
            case REQUESTCODE_TAKE:// 调用相机拍照
                if (resultCode == RESULT_OK) {
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){


//                        Log.e("REQUESTCODE_TAKE===0", "==="+data.getData());

                        File temp = new File(Environment.getExternalStorageDirectory() + "/" + IMAGE_FILE_NAME);

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                        File temp = new File(Environment.getExternalStorageDirectory() + "/images/" + IMAGE_FILE_NAME);

                            if (Uri.fromFile(temp) != null) {
                                urlpath = getRealFilePath(Uri.fromFile(temp));
                                Log.e("REQUESTCODE_TAKE===", temp+"==="+Uri.fromFile(temp)+"==="+urlpath);


                                File imgUri = new File(GetImagePath.getPath(context, Uri.fromFile(temp)));
                                Uri dataUri = FileProvider.getUriForFile(context, getPackageName() + ".fileprovider", imgUri);

                                Log.e("REQUESTCODE_TAKE===1", imgUri+"==="+dataUri);

                                startPhotoZoom(dataUri);


                            }
                        } else {
                            urlpath = getRealFilePath(Uri.fromFile(temp));
                            startPhotoZoom(Uri.fromFile(temp));
                        }

//                        File imgUri = new File(GetImagePath.getPath(context, data.getData()));

                    }else {
                        Toast.makeText(context,"未找到存储卡，无法存储照片！",Toast.LENGTH_SHORT).show();
                    }
                }



                break;
            case REQUESTCODE_CUTTING:// 取得裁剪后的图片
                if (data != null) {
                    setPicToView(data);
                }
                break;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    void compress(){
        // 设置参数
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 只获取图片的大小信息，而不是将整张图片载入在内存中，避免内存溢出
        BitmapFactory.decodeFile(urlpath, options);
        int height = options.outHeight;
        int width= options.outWidth;
        int inSampleSize = 3; // 默认像素压缩比例，压缩为原图的1/2
//        int minLen = Math.min(height, width); // 原图的最小边长
//        if(minLen > 100) { // 如果原始图像的最小边长大于100dp（此处单位我认为是dp，而非px）
//            float ratio = (float)minLen / 100.0f; // 计算像素压缩比例
//            inSampleSize = (int)ratio;
//        }
        options.inJustDecodeBounds = false; // 计算好压缩比例后，这次可以去加载原图了
        options.inSampleSize = inSampleSize; // 设置为刚才计算的压缩比例
        upBitmap = BitmapFactory.decodeFile(urlpath, options); // 解码文件

//        ByteArrayOutputStream bos=new ByteArrayOutputStream();
//        upBitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);//参数100表示不压缩
    }

    //获取资源文件中的图片
    public byte[] getByte() {
//        Resources res = getResources();
//        Bitmap bm = BitmapFactory.decodeResource(res, R.drawable.bike3);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        bm.compress(Bitmap.CompressFormat.PNG, 80, baos);
        LogUtil.e("getByte===1", upBitmap+"===");
        upBitmap.compress(Bitmap.CompressFormat.PNG, 50, baos);
//        upBitmap.compress(Bitmap.CompressFormat.PNG, 10, baos);
        LogUtil.e("getByte===2", upBitmap+"==="+baos.toByteArray().length);

//        QiNiuInitialize.getSingleton().put(getByte(), null, upToken, upCompletionHandler, uploadOptions);

        return baos.toByteArray();
    }

    private void setPicToView(Intent data) {
        m_myHandler.post(new Runnable() {
            @Override
            public void run() {
//                Bundle extras = data.getExtras();
                if (imageUri != null) {
                    urlpath = getRealFilePath(imageUri);    ///sdcard/temp.jpg

                    compress();

                    headerImageView.setImageBitmap(upBitmap);

                    Log.e("setPicToView===", imageUri+"==="+urlpath+"==="+upBitmap);

//                    uploadImage();    TODO

                    Log.e("pia===setPicToView", "==="+urlpath);

                }
            }
        });
    }

    public void startPhotoZoom(Uri uri) {
        Log.e("pia=startPhotoZoom", Build.VERSION.SDK_INT+"==="+uri);

        if (uri == null) {
            return;
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Log.e("pia=startPhotoZoom1", Build.VERSION.SDK_INT+"==="+uri);

            imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME));
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }

        Log.e("minef=startPhotoZoom", imageUri+"==="+uri);

        intent.setDataAndType(uri, "image/*");
        // crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
//        intent.putExtra("outputX", 600);
//        intent.putExtra("outputY", 600);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        intent.putExtra("circleCrop", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        startActivityForResult(intent, REQUESTCODE_CUTTING);
    }

    public String getRealFilePath(final Uri uri) {
        if (null == uri)
            return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
//            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);

            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);

                        Log.e("getRealFilePath===", cursor+"==="+data);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            submit();
//            nameEdit.setFocusable(false);
//            scrollToFinishActivity();

            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
